package conn

import (
	"database/sql"
	"github.com/go-ini/ini"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"strconv"
	"strings"
)

type Configs struct {
	MySQL MySQLConfig `ini:"mysql"`
}
type MySQLConfig struct {
	Host     string `ini:"host"`
	Port     int    `ini:"port"`
	User     string `ini:"user"`
	Password string `ini:"password"`
	Database string `ini:"database"`
}

var Config Configs

var DB *sql.DB

func init() {
	cfg, err := ini.Load(".env")
	if err != nil {
		log.Fatal("请配置.env文件:", err)
	}
	cfg.MapTo(&Config)
	if Config.MySQL.Database == "" {
		log.Fatal("请配置数据库")
	}
	//构建连接："用户名:密码@tcp(IP:端口)/数据库?charset=utf8"
	path := strings.Join([]string{
		Config.MySQL.User,
		":",
		Config.MySQL.Password,
		"@tcp(", Config.MySQL.Host,
		":",
		strconv.Itoa(Config.MySQL.Port),
		")/",
		"information_schema",
		"?charset=utf8"},
		"")
	//打开数据库,前者是驱动名，所以要导入： _ "github.com/go-sql-driver/mysql"
	DB, _ = sql.Open("mysql", path)
	//设置数据库最大连接数
	DB.SetConnMaxLifetime(10)
	//设置上数据库最大闲置连接数
	DB.SetMaxIdleConns(5)
	//验证连接
	if err := DB.Ping(); err != nil {
		log.Fatalf("Connnect database fail! %+v", err)
		return
	}
	log.Println("Connect Mysql Success!")
}

func Tables() (s []string) {
	rows, err := DB.Query("SELECT TABLE_NAME FROM TABLES WHERE TABLE_SCHEMA=?", Config.MySQL.Database)
	defer func() {
		if rows != nil {
			rows.Close()
		}
	}()
	if err != nil {
		log.Fatal(err)
	}
	var name string
	for rows.Next() {
		if err = rows.Scan(&name); err != nil {
			log.Fatal(err)
		}
		s = append(s, name)
	}
	return
}
